//
//  weightDB.m
//  myselfTest
//
//  Created by Lucifer on 15-5-22.
//  Copyright (c) 2015年 xuxzhou. All rights reserved.
//

#import "WeightDB.h"
#import "AppDelegate.h"
@implementation WeightDB
#define kUserWeightTableName @"weightDB"

- (id) init {
    self = [super init];
    if (self) {
        //========== 首先查看有没有建立message的数据库，如果未建立，则建立数据库=========
        _db = [userDBManager defaultDBManager].dataBase;
        
    }
    return self;
}

/**
 * @brief 创建数据库
 */
- (void) createDataBase {
    FMResultSet * set = [_db executeQuery:[NSString stringWithFormat:@"select count(*) from sqlite_master where type ='table' and name = '%@'",kUserWeightTableName]];
    
    [set next];
    NSInteger count = [set intForColumnIndex:0];
    BOOL existTable = !!count;
    if (existTable) {
        // TODO:是否更新数据库
        NSLog(@"%@",@"数据库已经存在");
        [AppDelegate showStatusWithText:@"体重表单已经存在" duration:2];
    } else {
        // TODO: 插入新的数据库
        NSString * sql =[NSString stringWithFormat: @"CREATE TABLE %@ (uid INTEGER PRIMARY KEY AUTOINCREMENT  NOT NULL, notesDate VARCHAR(50), weightKG VARCHAR(50), eatKcal VARCHAR(50),sportKcal VARCHAR(50))",kUserWeightTableName]
        ;
        BOOL res = [_db executeUpdate:sql];
        if (!res) {
            NSLog(@"%@",@"数据库创建失败");
            [AppDelegate showStatusWithText:@"数据库创建失败" duration:2];
        } else {
            NSLog(@"%@",@"数据库创建成功");
            [AppDelegate showStatusWithText:@"数据库创建成功" duration:2];
        }
    }
}

/**
 * @brief 保存一条用户记录
 *
 * @param user 需要保存的用户数据
 */
- (void) saveWeightItem:(WeightItem *) weightItem {
    NSMutableString * query = [NSMutableString stringWithFormat:@"INSERT INTO %@",kUserWeightTableName];
    NSMutableString * keys = [NSMutableString stringWithFormat:@" ("];
    NSMutableString * values = [NSMutableString stringWithFormat:@" ( "];
    NSMutableArray * arguments = [NSMutableArray arrayWithCapacity:8];
    if (weightItem.notesDate) {
        [keys appendString:@"notesDate,"];
        [values appendString:@"?,"];
        [arguments addObject:weightItem.notesDate];
    }
    if (weightItem.weightKG) {
        [keys appendString:@"weightKG,"];
        [values appendString:@"?,"];
        [arguments addObject:weightItem.weightKG];
    }
    if (weightItem.eatKcal) {
        [keys appendString:@"eatKcal,"];
        [values appendString:@"?,"];
        [arguments addObject:weightItem.eatKcal];
    }
    if (weightItem.sportKcal) {
        [keys appendString:@"sportKcal,"];
        [values appendString:@"?,"];
        [arguments addObject:weightItem.sportKcal];
    }
    [keys appendString:@")"];
    [values appendString:@")"];
    [query appendFormat:@" %@ VALUES%@",
     [keys stringByReplacingOccurrencesOfString:@",)" withString:@")"],
     [values stringByReplacingOccurrencesOfString:@",)" withString:@")"]];
    NSLog(@"%@",query);
    [AppDelegate showStatusWithText:@"插入一条数据" duration:2.0];
    [_db executeUpdate:query withArgumentsInArray:arguments];
}

/**
 * @brief 删除一条用户数据
 *
 * @param uid 需要删除的用户的id
 */
- (void) deleteWeightItemWithId:(NSString *)uid {
    NSString * query = [NSString stringWithFormat:@"DELETE FROM %@ WHERE uid = '%@'",kUserWeightTableName,uid];
    [AppDelegate showStatusWithText:@"删除一条数据" duration:2.0];
    [_db executeUpdate:query];
}

/**
 * @brief 修改用户的信息
 *
 * @param user 需要修改的用户信息
 */
- (void) mergeWithweightItem:(WeightItem *)weightItem{
    if (!weightItem.uid) {
        return;
    }
    NSString * query = [NSString stringWithFormat:@"UPDATE %@ SET",kUserWeightTableName];
    NSMutableString * temp = [NSMutableString stringWithCapacity:20];
    // xxx = xxx;
    if (weightItem.notesDate) {
        [temp appendFormat:@" notesDate = '%@',",weightItem.notesDate];
    }
    if (weightItem.weightKG) {
        [temp appendFormat:@" weightKG = '%@',",weightItem.weightKG];
    }
    if (weightItem.eatKcal) {
        [temp appendFormat:@" eatKcal = '%@',",weightItem.eatKcal];
    }
    if (weightItem.sportKcal) {
        [temp appendFormat:@" sportKcal = '%@',",weightItem.sportKcal];
    }
    [temp appendString:@")"];
    query = [query stringByAppendingFormat:@"%@ WHERE uid = '%@'",[temp stringByReplacingOccurrencesOfString:@",)" withString:@""],weightItem.uid];
    NSLog(@"%@",query);
    
    [AppDelegate showStatusWithText:@"修改一条数据" duration:2.0];
    [_db executeUpdate:query];
}

/**
 * @brief 模拟分页查找数据。取uid大于某个值以后的limit个数据
 *
 * @param uid
 * @param limit 每页取多少个
 */
- (NSArray *) findWithUid:(NSString *) uid limit:(int) limit {
    NSString * query = [NSString stringWithFormat:@"SELECT uid,notesDate,weightKG,eatKcal,sportKcal FROM %@",kUserWeightTableName ];
    if (!uid) {
        query = [query stringByAppendingFormat:@" ORDER BY uid DESC limit %d",limit];
    } else {
        query = [query stringByAppendingFormat:@" WHERE uid > %@ ORDER BY uid DESC limit %d",uid,limit];
    }
    
    FMResultSet * rs = [_db executeQuery:query];
    NSMutableArray * array = [NSMutableArray arrayWithCapacity:[rs columnCount]];
    while ([rs next]) {
        WeightItem * weightitem = [WeightItem new];
        weightitem.uid = [rs stringForColumn:@"uid"];
        weightitem.notesDate = [rs stringForColumn:@"notesDate"];
        weightitem.weightKG = [rs stringForColumn:@"weightKG"];
        weightitem.eatKcal = [rs stringForColumn:@"eatKcal"];
        weightitem.sportKcal=[rs stringForColumn:@"sportKcal"];
        [array addObject:weightitem];
    }
    [rs close];
    return array;
}
-(WeightItem *)findWithNoteDate:(NSString *)noteDate{
    NSString * query = [NSString stringWithFormat:@"SELECT * FROM %@",kUserWeightTableName ];
    query = [query stringByAppendingFormat:@" WHERE notesDate > %@ ",noteDate];
    
    FMResultSet * rs = [_db executeQuery:query];
    WeightItem * weightitem;
    while ([rs next]) {
       weightitem = [WeightItem new];
        weightitem.uid = [rs stringForColumn:@"uid"];
        weightitem.notesDate = [rs stringForColumn:@"notesDate"];
        weightitem.weightKG = [rs stringForColumn:@"weightKG"];
        weightitem.eatKcal = [rs stringForColumn:@"eatKcal"];
        weightitem.sportKcal=[rs stringForColumn:@"sportKcal"];
    }
    [rs close];
    return  weightitem;

}
@end
